
//  VRAddressBookTool.m
//  VRDoctor
//
//  Created by Veer on 16/5/27.
//
//

#import "VRAddressBookTool.h"

#import <AddressBook/AddressBook.h>
#import "VRAddressBookModel.h"


@implementation VRAddressBookTool


/**
 *  获取通讯录数量
 */
+ (NSInteger)getContactsCount
{
    
    
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    //拿到所有联系人
    CFArrayRef peopleArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
    //数组数量
    CFIndex peopleCount = CFArrayGetCount(peopleArray);
    
    return peopleCount;
}


/**
 *  获取通讯录数据
 */
+ (NSMutableArray *)getContactsWithBlock:(void(^)(CGFloat progress))block
{
    
    NSMutableArray *contactModelArray = [NSMutableArray array];

    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    //拿到所有联系人
    CFArrayRef peopleArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
    //数组数量
    CFIndex peopleCount = CFArrayGetCount(peopleArray);
    for (int i = 0; i < peopleCount; i++) {
        //拿到一个人
        ABRecordRef person = CFArrayGetValueAtIndex(peopleArray, i);
        //拿到姓名
        //姓
        NSString *lastNameValue = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
        //名
        NSString *firstNameValue = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        
        //公司名kABPersonOrganizationProperty
        NSString *organizationNameValue = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonOrganizationProperty);
        
        //拿到多值电话
        ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
        //多值数量
        CFIndex phoneCount = ABMultiValueGetCount(phones);
        
        NSString *phoneValue = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phones, 0);
        
        firstNameValue = firstNameValue == nil ? @"": firstNameValue;
        lastNameValue = lastNameValue == nil ? @"": lastNameValue;
        NSString *nameStr = [NSString stringWithFormat:@"%@%@", firstNameValue, lastNameValue];
        if (nameStr.length == 0) {
            organizationNameValue = organizationNameValue == nil ? @"": organizationNameValue;
            nameStr = organizationNameValue;
        }
//        VRLog(@"%@:%@", nameStr, phoneValue);
        
//        VRAddressBookModel *model = [[VRAddressBookModel alloc] init];
//        model.name = nameStr;
//        model.phoneNumber = phoneValue;
//        [contactModelArray addObject:model];
        
        
        
        for (int j = 0; j < phoneCount ; j++) {
            //电话标签本地化(例如是住宅,工作等)
            NSString *phoneLabel = (__bridge_transfer NSString *)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phones, j));
            //拿到标签下对应的电话号码
            NSString *phoneValue = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phones, j);

            NSString *nameStr = [NSString stringWithFormat:@"%@%@", firstNameValue, lastNameValue];
            
            nameStr = (nameStr == nil || nameStr.length == 0) ? organizationNameValue : nameStr;

            if (phoneValue == nil) {
                phoneValue = @"";
            }
            
            if (nameStr == nil) {
                nameStr = @"";
            }
            NSDictionary *dict = @{@"name": nameStr, @"number" : phoneValue};
            [contactModelArray addObject:dict];
        }
        
        CFRelease(phones);
        
        if (block) {
            
            block(i * 1.0 / peopleCount);
        }
    }
    
    CFRelease(addressBook);
    CFRelease(peopleArray);
    
    return contactModelArray;
}


+ (NSMutableArray *) getFriendListDataBy:(NSMutableArray *)array{
    NSMutableArray *ans = [[NSMutableArray alloc] init];
    
    NSArray *serializeArray = [(NSArray *)array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {//排序
        int i;
        NSString *strA = ((VRAddressBookModel *)obj1).pinyin;
        NSString *strB = ((VRAddressBookModel *)obj2).pinyin;
        for (i = 0; i < strA.length && i < strB.length; i++) {
            char a = tolower([strA characterAtIndex:i]);
            char b = tolower([strB characterAtIndex:i]);
            if (a > b) {
                return (NSComparisonResult)NSOrderedDescending;//上升
            }
            else if (a < b)
            {
                return (NSComparisonResult)NSOrderedAscending;//下降
            }
        }
        
        if (strA.length > strB.length)
        {
            return (NSComparisonResult)NSOrderedDescending;
        }else if (strA.length < strB.length)
        {
            return (NSComparisonResult)NSOrderedAscending;
        }else
        {
            return (NSComparisonResult)NSOrderedSame;
        }
    }];
    
    char lastC = '1';
    NSMutableArray *data;
    NSMutableArray *oth = [[NSMutableArray alloc] init];
    for (VRAddressBookModel *user in serializeArray)
    {
        char c = tolower([user.pinyin characterAtIndex:0]);
        if (!isalpha(c)) {
            [oth addObject:user];
        }
        else if (c != lastC){
            lastC = c;
            if (data && data.count > 0) {
                [ans addObject:data];
            }
            
            data = [[NSMutableArray alloc] init];
            [data addObject:user];
        }
        else {
            [data addObject:user];
        }
    }
    if (data && data.count > 0)
    {
        [ans addObject:data];
    }
    if (oth.count > 0)
    {
        [ans addObject:oth];
    }
    return ans;
}


+ (NSMutableArray *)getFriendListSectionBy:(NSMutableArray *)array{
    
    NSMutableArray *section = [[NSMutableArray alloc] init];
    [section addObject:UITableViewIndexSearch];
    for (NSArray *item in array)
    {
        VRAddressBookModel *user = [item objectAtIndex:0];
        char c = [user.pinyin characterAtIndex:0];
        if (!isalpha(c)) {
            c = '#';
        }
        [section addObject:[NSString stringWithFormat:@"%c", toupper(c)]];
    }
    return section;
    
}


@end
